package com.mgq.netty.chat.handler;

import com.mgq.netty.chat.message.GroupChatRequestMessage;
import com.mgq.netty.chat.message.GroupChatResponseMessage;
import com.mgq.netty.chat.session.GroupSession;
import com.mgq.netty.chat.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * @author MaGuangQi
 * 群聊handler
 * @date 2021-12-08 21:10
 **/
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        String content = msg.getContent();
        String groupName = msg.getGroupName();
        String from = msg.getFrom();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
        membersChannel.forEach(channel -> {
            GroupChatResponseMessage message = new GroupChatResponseMessage(from,content);
            channel.writeAndFlush(message);
        });
    }
}
